/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Exploder.java]
 * Creation Date        [22-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_03_game.tankwar_local.version_7;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

/**
 * 爆炸
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Exploder {

	/** 爆炸产生的坐标 */
	private int x = 0;
	private int y = 0;

	/** 爆炸是否存在 */
	private boolean live = true;

	/** 辅助类帮助引入图片 */
	private static Toolkit tool = Toolkit.getDefaultToolkit();

	/**
	 * 爆炸图片 getSource方法不依赖于路径, 而依赖于classpath, 使用它可以轻松在web服务器上部署
	 */
	private static Image[] images = {
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/0.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/1.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/2.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/3.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/4.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/5.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/6.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/7.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/8.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/9.gif")),
			tool.getImage(Exploder.class.getClassLoader().getResource(
					"pkg_03_game/tankwar_local/images/10.gif")), };

	/**
	 * 解决第一次击中坦克不会产生爆炸的问题, 原因在于读取图片可能是异步的IO, 第一次画可能只是画一个虚拟的图片框, 因此可以通过提前画一张图片来解决
	 */
	private static boolean init = false;

	int step = 0;

	private final MainFrame client;

	public Exploder(int x, int y, MainFrame client) {
		super();
		this.x = x;
		this.y = y;
		this.client = client;
	}

	/**
	 * 绘制爆炸效果
	 * 
	 * @param g
	 */
	public void paint(Graphics g) {

		// 提前画图片. 避免第一个被击毁的坦克没有爆炸产生
		if (!init) {
			for (int i = 0; i < images.length; i++) {
				g.drawImage(images[i], -100, -100, null);
			}
			init = true;
		}

		// 当爆炸消失时停止绘制
		if (!live) {
			client.exploders.remove(this);
			return;
		}

		// 如果step等于直径数组的长度, 那么就不在绘制了
		if (step == images.length) {
			live = false;
			step = 0;
			return;
		}
		g.drawImage(images[step], x, y, null);
		step++;
	}

}
